from mitmproxy import http
from mitmproxy.tools.dump import DumpMaster
from mitmproxy.options import Options
from .. import config
from . import reg
from . import cert
import logging

logging.getLogger("mitmproxy").setLevel(logging.ERROR)

class MyAddon:
    def response(self, flow: http.HTTPFlow) -> None:
        """
        响应处理
        """
        # if "https://helpcenter.taobao.com/servicehall/platter/entry" in flow.request.pretty_url:
        if "https://www.baidu.com" in flow.request.pretty_url:
            print(f"Modifying response for {flow.request.pretty_url}")
            flow.response.status_code = 200
            print(flow.response.text)
async def start_proxy():
    # 安装证书
    cert.install_cert(r'app/resource/cert/mitmproxy-ca-cert.p12')
    # 启用代理
    reg.set_windows_proxy(enable=True)
    # 使用 Options 类而不是 dict
    opts = Options(
        listen_host="127.0.0.1",
        listen_port=config.PROXY_PORT,
    )

    # 关闭日志
    master = DumpMaster(options=opts, with_dumper=False, with_termlog=False)
    
    master.addons.add(MyAddon())
    await master.run()
    
def end_proxy():
    # 关闭代理
    reg.set_windows_proxy(enable=False)
    